class Log():
    __slots__ = ('__logger')
    __log_folder = None

    __lib_os = __import__('os', fromlist=('path', 'makedirs', 'getpid'))
    __lib_logging = __import__('logging')
    __lib_handlers = __import__('logging.handlers', fromlist=('TimedRotatingFileHandler',))
    __lib_time = __import__('time', fromlist=('localtime', 'strftime'))

    ERROR = __lib_logging.ERROR
    WARNING = __lib_logging.WARNING
    INFO = __lib_logging.INFO
    DEBUG = __lib_logging.DEBUG
    
    __formatter = __lib_logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
    __lock = __import__('threading', fromlist=('RLock',)).RLock()
    __config = None

    @classmethod
    def get(cls, name=__name__):
        if not cls.__lib_os.path.exists(cls.__log_folder):
            cls.__lib_os.mkdir(cls.__log_folder)

        logger = cls.__lib_logging.getLogger(name)
        with cls.__lock:
            if cls.__config is None:
                h = cls.__lib_logging.StreamHandler()
                h.setFormatter(cls.__formatter)
                cls.__config = (cls.DEBUG, (h,))
            level, handlers = cls.__config
        logger.setLevel(level)
        for handler in handlers:
            logger.addHandler(handler)
        return logger
    @classmethod
    def setup(cls, filename=None, level=ERROR, with_pid=False, with_console=False):
        if isinstance(filename, str) and filename:
            libos = cls.__lib_os
            log_date = cls.__lib_time.strftime('%Y%m%d', cls.__lib_time.localtime())
            name, ext = libos.path.splitext(filename)
            if with_pid:
                pid = libos.getpid()
                filename = '%s-%s%s' % (name + log_date, pid, ext)
                # suffix = '%%Y%%m%%d-%s.log' % pid
            else:
                filename = '%s-%s%s' % (name, log_date, ext)
                # suffix = '%Y%m%d.log'
            path = libos.path.split(filename)[0]
            if cls.__log_folder == None: cls.__log_folder = path
            if not libos.path.exists(path):
                libos.makedirs(path)
            fh = cls.__lib_handlers.TimedRotatingFileHandler(filename=filename, when='midnight', backupCount=20, encoding='utf-8')
            # fh.suffix = suffix
            fh.setFormatter(cls.__formatter)
            if with_console:
                ch = cls.__lib_logging.StreamHandler()
                ch.setFormatter(cls.__formatter)
                hs = (ch, fh)
            else:
                hs = (fh,)
        else:
            h = cls.__lib_logging.StreamHandler()
            h.setFormatter(cls.__formatter)
            hs = (h,)
        with cls.__lock:
            cls.__config = (level, hs)
    def __init__(self):raise

    